import Taro from '@tarojs/taro';
import apiConfig from './apiConfig'

//网络请求拦截器
const interceptor = function (chain) {
  const requestParams = chain.requestParams
  const { method, data, url } = requestParams
  let token = Taro.getStorageSync('token')//拿到本地缓存中存的token
  if (token) {
    requestParams.header = {
      ...requestParams.header,
      Authorization: 'Bearer ' + token //将token添加到头部
    }
  }
  Taro.showLoading({
    title: '加载中...',
    mask: true // 防止用户操作，遮盖页面
  });
  return chain.proceed(requestParams).then(res => { return res })
}

Taro.addInterceptor(interceptor)

const request = async (method, url, params) => {
  //由于post请求时习惯性query参数使用params，body参数使用data，而taro只有data参数，使用contentType作为区分，因此此处需要做一个判断
  let contentType = params?.data ? 'application/json' : 'application/x-www-form-urlencoded';
  if (params) contentType = params?.headers?.contentType || contentType;
  const option = {
    method,
    isShowLoading: true,
    url: apiConfig.baseUrl + url,
    data: params && (params?.data || params?.params),
    header: {
      'content-type': contentType,
    },
    success(res) {
      Taro.hideLoading()
      //根据不同返回状态值3进行操作
      if (res.statusCode !== 200) {
        let returnMsg = '请求失败';
        const code = res.statusCode
        switch (code) {
          case 400:
            returnMsg = res.data.message || '请求错误';
            break;
          case 401:
            // 登录过期，跳转去登录
            Taro.setStorageSync('token', '');
            Taro.setStorageSync('verification_pass', false);
            Taro.navigateTo({ url: '/pages/login/index' });
            returnMsg = '未授权，请重新登录';
            break;
          case 403:
            returnMsg = '拒绝访问';
            break;
          case 404:
            returnMsg = '请求地址出错';
            break;
          case 500:
            returnMsg = '服务器内部错误';
            break;
          case 500:
            returnMsg = '服务器内部错误';
            break;
          default:
            returnMsg = '网络错误';
        }
        Taro.showToast({
          title: returnMsg,
          icon: 'none',
          duration: 2000
        });
      }
    },
    error(error) {
      let errorMsg = error?.message || '请求失败';
      Taro.showToast({
        title: errorMsg,
        icon: 'none',
        duration: 2000
      });
    }
  }
  const resp = await Taro.request(option);
  return resp.data;//根据个人需要返回
}

export default {
  get: (url, config = {}) => {
    return request('GET', url, config);
  },
  post: (url, config = {}) => {
    return request('POST', url, config);
  },
  put: (url, config = {}) => {
    return request('PUT', url, config);
  },
  delete: (url, config = {}) => {
    return request('DELETE', url, config);
  },
  patch: (url, config = {}) => {
    return request('PATCH', url, config);
  },
}
